<script setup lang="ts">
import { ElTree, ElSelectV2 } from 'element-plus'
import { ref, PropType, watch } from 'vue'

const props = defineProps({
  treeProps: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  treeData: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  nodeKey: {
    type: String as PropType<string>,
    default: () => ''
  }
})

const newRow = ref({})

const newTreeData = ref<any>([])
const newNodeKey = ref('')
const defaultProps = ref({})
const treeRef = ref<ComponentRef<typeof ElTree>>()
const value = ref({})

const options = [
  {
    value: '1',
    label: '没有权限'
  },
  {
    value: '2',
    label: '本人'
  },
  {
    value: '3',
    label: '本部门'
  },
  {
    value: '4',
    label: '本级及下级部门'
  },
  {
    value: '5',
    label: '全部'
  }
]

defineExpose({
  getCheckedKeys() {
    return treeRef.value!.getCheckedKeys(true)
  },
  getCheckedNodes() {
    console.log('getCheckedNodes', value.value)
    return value.value
  },
  setCheckedKeys(ids) {
    // console.log('setCheckedKeys', ids)
    value.value = ids
  },
  row: newRow.value
})

watch(
  () => props.treeProps,
  (value) => {
    if (!value) return
    defaultProps.value = value
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.treeData,
  (value) => {
    if (!value) return
    newTreeData.value = value
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.nodeKey,
  (value) => {
    if (!value) return
    newNodeKey.value = value
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <ElTree
    ref="treeRef"
    :data="newTreeData"
    :props="defaultProps"
    :expand-on-click-node="false"
    :node-key="newNodeKey"
    default-expand-all
  >
    <template #default="{ node, data }">
      <span class="custom-tree-node">
        <span>{{ node.label }}</span>
        <span>
          <ElSelectV2
            v-model="value[data.da_id]"
            :options="options"
            placeholder="Please select"
            size="small"
          />
        </span>
      </span>
    </template>
  </ElTree>
</template>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
